<template>
  <div>
    <div class="mt-4">
      <el-form inline>
        <el-row>
          <el-col :span="8">
            <el-form-item>
              <el-input
                  placeholder="请输入客户姓名"
                  v-model="searchKeyword"
                  clearable
                  @clear="getCustomerList"
              >
                <template #append>
                  <el-button :icon="Search" @click="getCustomerList" />
                </template>
              </el-input>
            </el-form-item>
          </el-col>
          <!-- 新增按钮 -->
          <el-button type="primary" @click="showAddDialog">新增</el-button>
        </el-row>
      </el-form>

      <div>
        <el-table
            :data="customerList"
            border
            stripe
            @row-click="handleRowClick"
        >
          <el-table-column type="index" label="序号" width="80" />
          <el-table-column prop="customer_name" label="姓名" />
          <el-table-column prop="customer_sex" label="性别" width="80">
            <template #default="scope">
              {{ scope.row.customer_sex === 0 ? '男' : '女' }}
            </template>
          </el-table-column>
          <el-table-column prop="customer_age" label="年龄" width="80" />
          <el-table-column prop="preferences" label="平时喜好" />
          <el-table-column prop="attention" label="注意事项" />
          <el-table-column prop="remark" label="备注" />
          <el-table-column label="操作" width="150px">
            <template #default="scope">
              <el-button
                  type="primary"
                  size="small"
                  @click="showEditDialog(scope.row.id)"
              >
                修改
              </el-button>
              <el-button
                  type="danger"
                  size="small"
                  @click="removeOne(scope.row.customer_id)"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 新增对话框 -->
      <el-dialog
          v-model="addDialog"
          title="新增客户偏好信息"
          width="40%"
          class="custom-dialog"
      >
        <el-form
            :model="newPreference"
            label-width="120px"
            class="custom-form"
            @submit.native.prevent
        >
          <!-- 客户选择 -->
          <el-form-item label="选择客户">
            <el-select
                v-model="newPreference.customer_id"
                placeholder="请选择客户"
                filterable
                clearable
            >
              <el-option
                  v-for="customer in customerOptions"
                  :key="customer.id"
                  :label="customer.customerName"
                  :value="customer.id"
              />
            </el-select>
          </el-form-item>

          <!-- 平时喜好 -->
          <el-form-item label="平时喜好">
            <el-input v-model="newPreference.preferences" class="form-input" />
          </el-form-item>

          <!-- 注意事项 -->
          <el-form-item label="注意事项">
            <el-input v-model="newPreference.attention" class="form-input" />
          </el-form-item>

          <!-- 备注 -->
          <el-form-item label="备注">
            <el-input v-model="newPreference.remark" class="form-input" />
          </el-form-item>
        </el-form>
        <template #footer>
          <el-button @click="closeAddDialog">取消</el-button>
          <el-button type="primary" @click="addOne">提交</el-button>
        </template>
      </el-dialog>

      <!-- 编辑对话框 -->
      <el-dialog
          v-model="editDialog"
          :title="dialogTitle"
          width="40%"
          class="custom-dialog"
      >
        <el-form
            :model="editCustomer"
            label-width="120px"
            class="custom-form"
            @submit.native.prevent
        >
          <el-form-item label="姓名">
            <el-input v-model="editCustomer.customer_name" class="form-input" disabled />
          </el-form-item>
          <el-form-item label="性别">
            <el-select
                v-model="editCustomer.customerSexText"
                placeholder="请选择性别"
                @change="handleSexChange"
                disabled
            >
              <el-option label="男" value="男"></el-option>
              <el-option label="女" value="女"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="年龄">
            <el-input v-model="editCustomer.customer_age" class="form-input" disabled />
          </el-form-item>
          <el-form-item label="平时喜好">
            <el-input v-model="editCustomer.preferences" class="form-input" />
          </el-form-item>
          <el-form-item label="注意事项">
            <el-input v-model="editCustomer.attention" class="form-input" />
          </el-form-item>
          <el-form-item label="备注">
            <el-input v-model="editCustomer.remark" class="form-input" />
          </el-form-item>
        </el-form>
        <template #footer>
          <el-button
              @click="editOne"
              type="primary"
              class="dialog-footer-button"
          >
            提交
          </el-button>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, reactive } from 'vue';
import { Plus, Search } from '@element-plus/icons-vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import http from '@/axios/http'; // 假设已经配置好axios

const searchKeyword = ref('');
const customerList = ref([]);
const editDialog = ref(false);
const addDialog = ref(false);
let dialogTitle = reactive('');

const editCustomer = reactive({
  customer_id: null, // 新增 customer_id
  id: null,
  customer_name: '',
  customer_sex: null,
  customerSexText: '', // 新增：存储显示文本（男/女）
  customer_age: null,
  preferences: '',
  attention: '',
  remark: ''
});

function handleSexChange(sexText) {
  editCustomer.customer_sex = sexText === '男' ? 0 : 1;
}

const newPreference = reactive({
  customer_id: null,
  preferences: '',
  attention: '',
  remark: ''
});

const customerOptions = ref([]);

function showAddDialog() {
  addDialog.value = true;
}

function closeAddDialog() {
  addDialog.value = false;
  Object.keys(newPreference).forEach(key => newPreference[key] = null);
}

const getCustomerList = async () => {
  try {
    const params = {
      keyword: searchKeyword.value || '%'
    };
    const res = await http.post('/lyy/get_CustomerPreference_List', params);
    if (res.data.result === 'success') {
      customerList.value = res.data.data.map(item => ({
        id: item.id,
        customer_id: item.customer?.id, // 获取 customer_id
        customer_name: item.customer?.customerName, // 从嵌套的 customer 对象中获取 customerName
        customer_sex: item.customer?.customerSex,  // 从嵌套的 customer 对象中获取
        customer_age: item.customer?.customerAge,  // 从嵌套的 customer 对象中获取
        preferences: item.preferences,
        attention: item.attention,
        remark: item.remark
      }));
      if (customerList.value.length === 0) {
        ElMessage.info('没有找到匹配的客户数据');
      }
      // 调用过滤函数更新顾客选项列表
      filterCustomerOptions();
    } else {
      ElMessage.error('获取客户数据失败：' + res.data.error);
    }
  } catch (error) {
    console.error('请求后端接口失败：', error);
    ElMessage.error('请求后端接口失败，请稍后重试');
  }
};

// 获取客户列表（用于选择）
async function getCustomerOptions() {
  try {
    const res = await http.get('/lyy/get_Customer_List'); // 假设后端提供此接口
    if (res.data.result === 'success') {
      customerOptions.value = res.data.data.map(customer => ({
        id: customer.id,
        customerName: customer.customerName // 只提取 customerName
      }));
      // 调用过滤函数更新顾客选项列表
      filterCustomerOptions();
    } else {
      ElMessage.error('获取客户列表失败：' + res.data.error);
    }
  } catch (error) {
    console.error('请求后端接口失败：', error);
    ElMessage.error('请求后端接口失败，请稍后重试');
  }
}

// 过滤已有喜好的顾客
function filterCustomerOptions() {
  const existingCustomerIds = customerList.value.map(item => item.customer_id);
  customerOptions.value = customerOptions.value.filter(customer =>!existingCustomerIds.includes(customer.id));
}

// 提交新增操作
function addOne() {
  return new Promise((resolve, reject) => {
    const requestData = {
      customerId: newPreference.customer_id,
      preferences: newPreference.preferences,
      attention: newPreference.attention,
      remark: newPreference.remark
    };
    http.post('/lyy/addCustomerPreference', requestData)
        .then(res => {
          if (res.data.result === 'success') {
            ElMessage.success('新增成功');
            closeAddDialog();
            getCustomerList(); // 刷新客户列表
            resolve();
          } else {
            ElMessage.error('新增失败: ' + res.data.error);
            reject();
          }
        })
        .catch(error => {
          console.error('新增失败:', error);
          ElMessage.error('新增失败，请稍后重试');
          reject();
        });
  });
}

function showEditDialog(id) {
  const targetCustomer = customerList.value.find(item => item.id === id);
  if (targetCustomer) {
    Object.assign(editCustomer, {
      id: targetCustomer.id,
      customer_id: targetCustomer.customer_id, // 赋值 customer_id
      customer_name: targetCustomer.customer_name, // 从 customer 对象中提取
      customer_sex: targetCustomer.customer_sex,  // 从 customer 对象中提取
      // 根据数值设置显示文本
      customerSexText: targetCustomer.customer_sex === 0 ? '男' : '女',
      customer_age: targetCustomer.customer_age,  // 从 customer 对象中提取
      preferences: targetCustomer.preferences,
      attention: targetCustomer.attention,
      remark: targetCustomer.remark
    });
    editDialog.value = true;
    dialogTitle = '修改客户信息';
  }
}

function closeEditDialog() {
  editDialog.value = false;
  Object.keys(editCustomer).forEach(key => delete editCustomer[key]);
  editCustomer.id = null;
  editCustomer.customer_id = null; // 清空 customer_id
}

function editOne() {
  return new Promise((resolve, reject) => {
    const requestData = {
      customer_id: editCustomer.customer_id, // 使用 customer_id
      preferences: editCustomer.preferences,
      attention: editCustomer.attention,
      remark: editCustomer.remark
    };
    console.log("requestData", requestData);
    http.post('/lyy/editCustomer', requestData)
        .then(res => {
          if (res.data.result === 'success') {
            ElMessage.success('修改成功');
            closeEditDialog();
            getCustomerList();
            resolve();
          } else {
            ElMessage.error('修改失败: ' + res.data.error);
            reject();
          }
        })
        .catch(error => {
          console.error('修改失败:', error);
          ElMessage.error('修改失败，请稍后重试');
          reject();
        });
  });
}

// 删除一条数据
const removeOne = (customerId) => {
  ElMessageBox.confirm('确定要删除该记录吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
      .then(async () => {
        try {
          console.log("Deleting customer with customer_id:", customerId); // 打印 customer_id
          const res = await http.post('/lyy/deleteCustomer', { customer_id: customerId });
          if (res.data.result === 'success') {
            ElMessage.success('删除成功');
            await getCustomerList();
            // 删除成功后重新获取顾客选项列表
            await getCustomerOptions();
          } else {
            ElMessage.error('删除失败: ' + res.data.error);
          }
        } catch (error) {
          console.error('删除失败:', error);
          ElMessage.error('删除失败，请稍后重试');
        }
      })
      .catch(() => {
        ElMessage.info('已取消删除');
      });
};

function handleRowClick(row) {
  // 点击表格行时，可以选择是否进行一些操作，比如展开详细信息等，这里暂未实现具体逻辑
}

onMounted(() => {
  getCustomerList();
  getCustomerOptions();
});
</script>

<style scoped>
.mt-4 {
  margin-top: 16px;
}

.add-button {
  margin-left: 10px;
}

.custom-dialog {
  padding: 20px;
  box-sizing: border-box;
}

.custom-form {
  width: 100%;
}

.form-input {
  width: 100%;
}

.dialog-footer-button {
  float: right;
  margin: 0;
  padding: 10px 20px;
}
</style>